#include<iostream>
#include<cstring>
#include<queue>
using namespace std;

typedef pair<int, int> PII;

const int N = 150010;
int h[N], e[N], ne[N], w[N], idx;
int d[N];
bool st[N];
priority_queue<PII, vector<PII>,greater<PII>> q;

void add(int a,int b ,int c) {
  e[idx] = b;
  ne[idx] = h[a];
  w[idx] = c;
  h[a] = idx ++;
}

int dijkstra(int n) {
  memset(d, 0x3f3f3f3f, sizeof d);
  d[1] = 0;
  q.push({ 0, 1 });
  while(q.size()) {
    auto t = q.top();
    q.pop();
    if(st[t.second]) continue;
    st[t.second] = true;
    for(int i = h[t.second];i != -1;i = ne[i]) {
      int v = e[i];
      if (d[v] > t.first + w[i]) {
        d[v] = t.first + w[i];
        q.push({ d[v], v });
      }
    }
  }
  if (d[n] == 0x3f3f3f3f) return -1;
  return d[n];
}

int main() {
  int n, m;
  cin >> n >> m;
  memset(h, -1, sizeof h);
  while (m --) {
    int a, b, c;
    scanf("%d%d%d", &a, &b, &c);
    add(a, b, c);
  }
  cout << dijkstra( n );
  return 0;
}
